#!/usr/bin/perl
# 
#  Exercise 7.7 
# 
# Sometimes not all choices are equally likely to be picked in a random selection. Write a subrou-
# tine that randomly returns a nucleotide, in which the probability of each nucleotide 
# can be specified. Pass the subroutine four numbers as arguments, representing the 
# probabilities of each nucleotide; if each probability is 0.25, the subroutine is 
# equally likely to pick each nucleotide. As error checking, have the subroutine 
# ensure that the sum of the four probabilities is 1.
# 
# Hint: one way to accomplish this is to divide the range between 0 and 1 into four 
# intervals with lengths corresponding to the probability of the respective nucle-
# otides. Then, simply pick a random number between 0 and 1, see in which interval 
# it falls, and return the corresponding nucleotide.
#
# Answer to Exercise 7.7

use strict;
use warnings;

srand(time|$$);

for(my $i = 0 ; $i < 30 ; ++$i) {
	print distribution(0.02, 0.45, 0.42, 0.11), "\n";
}

exit;

sub distribution {

	my(@probability) = @_;

	unless( $probability[0] + $probability[1] + $probability[2] + $probability[3] == 1) {
		print "Sum of probabilites must equal 1!\n";
		exit;
	}

	my $randnum = rand(1);

	if($randnum < $probability[0]) {
		return 'A';
	}elsif($randnum < $probability[0] + $probability[1]) {
		return 'C';
	}elsif($randnum < $probability[0] + $probability[1] + $probability[2]) {
		return 'G';
	}else{
		return 'T';
	}
}
